package com.hsd.netty.server.handler;

import com.hsd.netty.server.common.NettyHeader;
import com.hsd.netty.server.common.NettyMessage;
import com.hsd.netty.server.enums.MessageType;
import com.hsd.netty.server.strategy.MessageHandlerAdapter;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author s.he
 * on 2020/6/6
 */
@Service
@ChannelHandler.Sharable
public class LoginFilterServerHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private MessageHandlerAdapter messageHandlerAdapter;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage nettyMessage = (NettyMessage)msg;
        NettyHeader nettyHeader = nettyMessage.getNettyHeader();
        byte type = nettyHeader.getType();
        MessageType messageType = MessageType.getMessageType(type);
        NettyMessage result = messageHandlerAdapter.handler(type, ctx, nettyMessage);
        //如果是心跳和登录，则直接在这边返回，如果是正常的请求报文，则需要跳转到下一个节点
        if(!messageType.equals(MessageType.REQUEST)) {
            ctx.writeAndFlush(result);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.channel().close();
    }
}
